package woaini.fenger.core.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.GlobalInterceptor;
import cn.hutool.http.HttpGlobalConfig;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import woaini.fenger.core.base.boot.ApplicationStartupCompleted;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * HTTP配置
 *
 * @see woaini.fenger.core.config.HttpConfig
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@Component
@Slf4j
public class HttpConfig implements ApplicationStartupCompleted {
    @Override
    public void onInit() {
        //切面日志
        GlobalInterceptor.INSTANCE.addRequestInterceptor(request -> {
            Map<String, List<String>> headers = request.headers();
            StringBuilder headerBuilder = new StringBuilder();
            headers.forEach((k, v) -> {
                headerBuilder.append(k + ":" + v.get(0) + "\n");
            });
            log.info("{}请求:{},参数:{},请求头:{}", request.getMethod(),request.getUrl(),StrUtil.str(request.bodyBytes(), StandardCharsets.UTF_8), headerBuilder);
        });
        GlobalInterceptor.INSTANCE.addResponseInterceptor(response -> {
            log.info("返回:{},请求头:{}",response.body(), JSONObject.toJSONString(response.headers()));
        });
        //超时时间 14S
        HttpGlobalConfig.setTimeout(7000);
    }
}
